﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using ZG_member.BLL;
using System.Windows.Forms.DataVisualization.Charting;

namespace ZG_member
{
    public partial class CustomerContributeChart : Form
    {
        public CustomerContributeChart()
        {
            InitializeComponent();
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"];
            this.Opacity = 0;
        }

        private void CustomerContributeChart_Load(object sender, EventArgs e)
        {
            this.timer1.Start();
            bindClbxMemberLevel();

            Series s1 = new Series("贡献总额");
            chart1.Series.Add(s1);
            chart1.Series["贡献总额"].IsValueShownAsLabel = true;

        }

        public void bindClbxMemberLevel()
        {
            consumeSolution solution = new consumeSolution();
            DataTable dt = solution.GetList("").Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                clbxMemberLevel.Items.Add(dt.Rows[i]["solutionName"].ToString(), true);
            }

            clbxMemberLevel.Update();
        }

        public void ExportExcel(string fileName, DataGridView myDGV)
        {

            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "*.xlsx|*.xlsx|*.xls|*.xls";
            saveDialog.FilterIndex = 2;
            saveDialog.FileName = fileName + "Excel导出" ;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;

            if (saveFileName.IndexOf(":") < 0)
            {
                return;
            }//被点了取消 
            else
            {
                //MessageBoxTimeout.Show("正在导出···，请稍等！", "系统提示", 2000);
            }
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的机子未安装Office.Excel组件");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
            //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    //fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁 
            MessageBox.Show(saveFileName + "的资料保存成功", "提示", MessageBoxButtons.OK);
        }


        private void btnsubmit_Click(object sender, EventArgs e)
        {
            memberInfo memInfo = new memberInfo();
            string unit = "";
            DataTable dt;

            int top;
            if (!int.TryParse(txtTop.Text, out top))
            {
                MessageBox.Show("请输入数字");
                return;
            }

            StringBuilder sb = new StringBuilder();
            string sign = "";
            for (int i = 0; i < clbxMemberLevel.Items.Count; i++)
            {
                if (clbxMemberLevel.GetItemChecked(i))
                {
                    sb.Append(sign);
                    sb.Append("'");
                    sb.Append(clbxMemberLevel.Items[i].ToString());
                    sb.Append("'");
                    sign = ",";
                }
            }
            if (sb.ToString() == "")
            {
                sb.Append("null");
            }

            dt = memInfo.GetListSql("select top " + top.ToString() + " memberId as 会员卡号,Balance+consume as 贡献总额,memberName as 会员姓名,(select solutionName from consumeSolution where id =cardType) as 卡片类型 from memberInfo where  cardType in (select id from consumeSolution where solutionName in (" + sb.ToString() + ")) order by Balance+consume desc").Tables[0];
            //chart1.ChartAreas["ChartArea1"].AxisX.Title = "用户贡献值";
            string aa = memInfo.Getheji(top.ToString(), sb.ToString());
            string[] aaa = { "合计", aa };
            dt.Rows.Add(aaa);
            dgvDate.DataSource = dt;


            //DataTable dtt = memInfo.GetListSql("select top " + top.ToString() + "memberId as 会员卡号1, Balance+consume as 贡献总额1,memberName as 会员姓名1,(select solutionName from consumeSolution where id =cardType) as 卡片类型 from memberInfo where  cardType in (select id from consumeSolution where solutionName in (" + sb.ToString() + ")) order by Balance+consume desc").Tables[0];
            //chart1.DataSource = null;
            chart1.DataSource = dt;
            chart1.Series["贡献总额"].XValueMember = "会员姓名";
            chart1.Series["贡献总额"].YValueMembers = "贡献总额";

            chart1.DataBind();

            chart1.ChartAreas["ChartArea1"].AxisX.Title = "用户贡献值";

            if ((dt.Rows.Count-1) > 9) //当X轴超过9时就会显示不完全
            {
                //设置X轴坐标的间隔为1
                chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
                //设置X轴坐标的偏移为1
                chart1.ChartAreas["ChartArea1"].AxisX.IntervalOffset = 1;
                //设置交错显示，例如数据多时可分两行显示
                chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.IsStaggered = true;
            }


            
            
            //string aa = memInfo.Getheji(top.ToString(), sb.ToString());
            //string[] aaa = { "合计" , aa};
            //dt.Rows.Add(aaa);
            //dgvDate.DataSource = dt;
            
            //dgvDate.Rows.add(aaa);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExportExcel(" ", dgvDate);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Left += 2;
            this.Opacity += 0.1;
            if (Opacity == 1)
            {
                this.timer1.Stop();

            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            this.Top = this.Top + 10;
            this.Opacity = this.Opacity - 0.06;
            if (Opacity <= 0)
            {
                this.timer2.Stop();
                this.Close();
            }
        }
        int flag = 0;
        private void CustomerContributeChart_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flag == 0)
            {
                e.Cancel = true;
                flag = 1;
                this.timer2.Start();
            }
        }

        private void txtTop_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                //if (e.KeyChar == '.')
                //{
                //    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                //        e.Handled = true;
                //}
                //else
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }
        }


    }
}
